#!usr/bin/env python
# *- coding:utf-8 -*-
# Andy Create @ 11/15/2019 11:13 AM

from api import models


class Network(object):
    def parse_network_data(self, name, network_info):
        data = {}
        data['name'] = name
        data['up'] = network_info['up']
        data['hwaddr'] = network_info['hwaddr']
        data['address'] = network_info['inet'][0]['address']
        data['netmask'] = network_info['inet'][0]['netmask']
        data['broadcast'] = network_info['inet'][0]['broadcast']
        return data

    def process(self, network, server_object):
        if not network['status']:
            print('网卡信息错误', network['error'])
            return
        network_info = network['data']
        new_network_name_set = set(network_info.keys())
        db_network_queryset = models.Network.objects.filter(server=server_object)
        db_network_dict = {obj.name: obj for obj in db_network_queryset}
        db_network_name_set = set(db_network_dict.keys())
        record_msg_list = []
        # 新增的网卡
        create_name_set = new_network_name_set - db_network_name_set
        create_object_list = []
        for name in create_name_set:
            data = self.parse_network_data(name, network_info[name])
            create_object_list.append(models.Network(**data, server=server_object))

        if create_object_list:
            models.Network.objects.bulk_create(create_object_list, batch_size=10)
            msg = "[新增网卡] 名%s" % ",".join(create_name_set)
            record_msg_list.append(msg)

        # 要删除的网卡
        remove_name_set = db_network_name_set - new_network_name_set
        if remove_name_set:
            msg = models.Network.objects.filter(server=server_object, name__in=remove_name_set).delete()
            record_msg_list.append(msg)

        # # 要更新输入的网卡
        update_name_set = new_network_name_set & db_network_name_set
        for name in update_name_set:
            temp = []
            row_network_info = self.parse_network_data(name, network_info[name])
            row_object = db_network_dict[name]
            for key, value in row_network_info.items():
                if value != getattr(row_object, key):
                    msg = "%s由%s变更为%s" % (key, getattr(row_object, key), value)
                    temp.append(msg)
                    setattr(row_object, key, value)
            if temp:
                name_msg = "[更新网卡]%s:%s" % (name, "".join(temp))
                record_msg_list.append(name_msg)
                row_object.save()

        if record_msg_list:
            models.Record.objects.create(server=server_object, content="\n".join(record_msg_list))
